#include "KDM3EventAction.hh"
#include "KDM3HitsCollection.hh"
#include "KDM3Hit.hh"
#include "KDM3Globals.hh"
#include "G4HCofThisEvent.hh"
#include "G4Event.hh"
#include "G4SDManager.hh"
#include "G4ThreeVector.hh"
#include "TH3D.h"
#include "TFile.h"
#include <sstream>
#include <iostream>
using namespace std;

KDM3EventAction::KDM3EventAction() {
	;
}

KDM3EventAction::~KDM3EventAction() {
	;
}

void KDM3EventAction::BeginOfEventAction(const G4Event*) {
	BHVeto = false;
	frontVeto = false;
	rearVeto = false;
	sideVeto = false;
	barrelVeto = false;
}

void KDM3EventAction::EndOfEventAction(const G4Event* event) {
	G4HCofThisEvent* hcc = event->GetHCofThisEvent();
	KDM3HitsCollection* hc = (KDM3HitsCollection*) (hcc->GetHC(0));
	size_t size = hc->GetSize();

	std::stringstream ss;
	ss << "eventNumber" << eventNum;
	G4String name = ss.str();

	TTree* tree = new TTree(name, name);
	TBranch* energyBranch = tree->Branch("energy", &photonEnergy, "energy/D");
	TBranch* BHVetoBranch = tree->Branch("BHVeto", &BHVeto, "veto/O");
	TBranch* frontVetoBranch = tree->Branch("frontVeto", &frontVeto, "veto/O");
	TBranch* rearVetoBranch = tree->Branch("rearVeto", &rearVeto, "veto/O");
	TBranch* sideVetoBranch = tree->Branch("sideVeto", &sideVeto, "veto/O");
	TBranch* barrelVetoBranch = tree->Branch("barrelVeto", &barrelVeto, "veto/O");

	energyBranch->Fill();
	BHVetoBranch->Fill();
	frontVetoBranch->Fill();
	rearVetoBranch->Fill();
	sideVetoBranch->Fill();
	barrelVetoBranch->Fill();

	dataForm* data = new dataForm;
	TBranch* branch = tree->Branch("photonNumber0", &(*data).energy, "energy/D:time:x:y:z");
	for (size_t i = 0; i < size; i++) {
		KDM3Hit* hit = (KDM3Hit*) hc->GetHit(i);
		(*data).energy = hit->GetEnergy();
		(*data).time = hit->GetTime();
		G4ThreeVector pos = hit->GetPosition();
		(*data).x = pos.x();
		(*data).y = pos.y();
		(*data).z = pos.z();
		branch->Fill();
	}

	tree->Write();
	tree->Delete();
	delete data;
}
